//
//  NSObject+Hook.m
//  HookDemo
//
//  Created by 杨鑫 on 2022/6/29.
//

#import "NSObject+Hook.h"
#import <objc/runtime.h>
#import <objc/message.h>

@implementation NSObject (Hook)

- (void)hook:(SEL)cmd
{
    Class class = object_getClass(self);
    NSString *subClassName = [NSString stringWithFormat:@"HOOK_%@", NSStringFromClass(class)];
    Class subClass = objc_allocateClassPair(class, subClassName.UTF8String, 0);
    objc_registerClassPair(subClass);
    object_setClass(self, subClass);
    
    Method method = class_getInstanceMethod(subClass, cmd);
    class_addMethod(subClass, cmd, (IMP)setterMethod, method_getTypeEncoding(method));
}

void setterMethod(id self, SEL _cmd, id obj)
{
    struct objc_super superClass = {
        self,
        class_getSuperclass(object_getClass(self))
    };
    objc_msgSendSuper(&superClass, _cmd, obj);
}

@end
